package com.nuaner.nfc;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.nuaner.nfc.card.CardManager;

public class Nfcard extends Activity implements OnClickListener {

	public static final int REFRESH_INFO = 0;
	public static final String IO_DATA = "From IO";
	private IntentFilter[] intentFilterArray;
	private String[][] techListsArray;
	private NfcAdapter nfcAdapter;
	private PendingIntent pendingIntent;
	
	public Handler handler;
	
	private int threads = 0;
	
	private TextView info;
	private EditText cmd;
	private Button btn_send;
	private Button btn_settings;
	private Tag tag;
	
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.nfcard);
		
		pendingIntent = PendingIntent.getActivity(
			    this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		IntentFilter ndefFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
		IntentFilter tagFilter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
		IntentFilter techFilter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
	    try {
	    	ndefFilter.addDataType("*/*");
	    } catch (MalformedMimeTypeException e) {
	        throw new RuntimeException("fail", e);
	    }
	    intentFilterArray = new IntentFilter[] {ndefFilter, tagFilter, techFilter};
	    
	    techListsArray = new String[][] { 
	    		new String[] { IsoDep.class.getName() },
	    		new String[] { MifareClassic.class.getName() },
	    		new String[] { MifareUltralight.class.getName() },
	    		new String[] { Ndef.class.getName() },
	    		new String[] { NdefFormatable.class.getName() },
	    		new String[] { NfcA.class.getName() },
	    		new String[] { NfcB.class.getName() },
	    		new String[] { NfcF.class.getName() },
	    		new String[] { NfcV.class.getName() }
	    };
	    
	    info = (TextView) this.findViewById(R.id.board);
	    info.setText("START:\n");
	    cmd = (EditText) this.findViewById(R.id.cmd);
	    btn_send = (Button) this.findViewById(R.id.cmd_send);
	    btn_settings = (Button) this.findViewById(R.id.settings);
	    
	    btn_send.setOnClickListener(this);
	    btn_settings.setOnClickListener(this);
	    
	    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
	    handler = new Handler() {   
	         public void handleMessage(Message msg) {    
	        	 switch (msg.what) {    
                 	case REFRESH_INFO:  
                 		String boardtext = (String) info.getText();
                	    boardtext += "Threads Number: " + ++threads;
                	    boardtext += msg.getData().getString(IO_DATA);
                	    info.setText(boardtext);
                 		break;    
	        	 }    
	             super.handleMessage(msg);    
	         }    
	    }; 
	    onNewIntent(getIntent());
	}

	@Override
	protected void onNewIntent(Intent intent) {
		final Parcelable extra_tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		if(extra_tag != null) {
			Toast.makeText(this, "get_tag", Toast.LENGTH_LONG).show();
			new Thread(new Runnable() {
				public void run() {
					 if (!Thread.currentThread().isInterrupted()) { 
						 String data_IO = CardManager.load(Nfcard.this, (Tag)extra_tag);
						 Message message = new Message();    
						 message.what = REFRESH_INFO; 
						 Bundle bundle = new Bundle();
						 bundle.putString(IO_DATA, data_IO);
						 message.setData(bundle);
						 Nfcard.this.handler.sendMessage(message);   
					 }  
				}
			}).start();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (nfcAdapter != null)
			nfcAdapter.disableForegroundDispatch(this);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (nfcAdapter != null)
			nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilterArray, techListsArray);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.settings:
				startActivityForResult(new Intent(
						android.provider.Settings.ACTION_WIRELESS_SETTINGS), 0);
				break;
			case R.id.cmd_send:
				String cmdText = cmd.getText().toString();
				CommandShell.ExecuteCommand(tag, this.info, cmdText);
				break;
			default:
				break;
		}
	}
	
	

}
